#include"Game.h"

#define ROW 3
#define COL 3

static char chess_board[ROW][COL];

void InitGame()
{
	for (int i = 0; i < ROW; ++i)
	{
		for (int j = 0; j < COL; ++j)
		{
			chess_board[i][j] = ' ';
		}
	}
}

void PrintChess()
{
	for (int i = 0; i < ROW; ++i)
	{
		printf("| %c | %c | %c |\n", chess_board[i][0], chess_board[i][1], chess_board[i][2]);
		if (i < ROW - 1)
			printf("|---|---|---|\n");
	}
}

void PlayerMove()
{
	printf("玩家落子.\n");
	int row, col;
	while (1)
	{
		printf("请选择你要下的位置(row col):");
		scanf("%d %d", &row, &col);
		if (row < 0 || row >= ROW || col<0 || col>COL)
		{
			printf("坐标输入错误，请重新输入\n");
			continue;
		}
		if (chess_board[row][col] != ' ')
		{
			printf("此坐标已落子，请重新选择\n");
			continue;
		}
		chess_board[row][col] = 'x';
		break;
	}
}

void ComputerMove()
{
	srand(time(0));
	while (1)
	{
		int row = rand() % ROW;
		int col = rand() % COL;

		if (chess_board[row][col] != ' ')
		{
			continue;
		}
		chess_board[row][col] = 'o';
		break;
	}
}

bool ChessFull()
{
	for (int i = 0; i < ROW; ++i)
	{
		for (int j = 0; j < COL; ++j)
		{
			if (chess_board[i][j] == ' ')
				return false;
		}
	}
	return true;
}

char CheckGameOver()
{
	for (int i = 0; i < ROW; ++i)
	{
		if (chess_board[i][0] != ' '
			&& chess_board[i][0] == chess_board[i][1]
			&& chess_board[i][0] == chess_board[i][2])
			return chess_board[i][0];
	}
	for (int i = 0; i < COL; ++i)
	{
		if (chess_board[0][i] != ' '
			&& chess_board[0][i] == chess_board[1][i]
			&& chess_board[0][i] == chess_board[2][i])
			return chess_board[0][i];
	}
	if (chess_board[0][0] != ' '
		&& chess_board[0][0] == chess_board[1][1]
		&& chess_board[0][0] == chess_board[2][2])
		return chess_board[0][0];
	if (chess_board[0][2] != ' '
		&& chess_board[0][2] == chess_board[1][1]
		&& chess_board[0][2] == chess_board[2][0])
		return chess_board[0][2];

	if (ChessFull())
		return 'h';

	return 'c'; //
}

void StartGame()
{
	InitGame();

	char winner;
	while (1)
	{
		PrintChess();

		PlayerMove();
		winner = CheckGameOver();
		if (winner != 'c')
			break;

		ComputerMove();
		winner = CheckGameOver();
		if (winner != 'c')
			break;
	}
	if (winner == 'x')
		printf("玩家胜利\n");
	else if (winner == 'o')
		printf("电脑胜利\n");
	else if (winner == 'h')
		printf("平局\n");
}